﻿using System.Text;
using System.Security.Cryptography;

namespace Net8.Project.Common.Extensions
{
    public static class StringExtension
    {
        /// <summary>
        /// MD5加密 32位
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToMd5(this string str, string charset = "utf-8")
        {
            if (string.IsNullOrEmpty(str))
            {
                return string.Empty;
            }
            //创建md5对象
            byte[] inputBytes;
            byte[] hashBytes;
            //使用GB2312编码方式把字符串转化为字节数组．
            try
            {
                inputBytes = Encoding.GetEncoding(charset).GetBytes(str);
            }
            catch (Exception)
            {
                inputBytes = Encoding.GetEncoding("UTF-8").GetBytes(str);
            }
            hashBytes = MD5.HashData(inputBytes);
            var sb = new StringBuilder();
            foreach (var b in hashBytes)
            {
                // 格式后的字符是小写的字母，如果使用大写（X）则格式后的字符是大写字符 
                sb.Append(b.ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// MD5加密 16位
        /// </summary>
        /// <param name="encypStr"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string ToShortMd5(this string encypStr, string charset = "utf-8")
        {
            if (string.IsNullOrEmpty(encypStr))
                return "";
            return ToMd5(encypStr, charset).Substring(8, 16);
        }
    }
}
